<template>
  <div>
    <a-upload
      :file-list="dataGrid.fileList"
      :remove="handleRemove"
      :before-upload="beforeUpload"
      accept=".xlsx,.xls">
      <a-button> <a-icon type="upload" /> Select Excel File </a-button>
    </a-upload>

  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  name: 'Upexcel',
  components: {
    XLSX
  },
  data () {
    return {
      dataGrid: '',
      data: ''
    }
  },
  methods: {
    handleRemove () {},
    beforeUpload (file) {
      let result = ''
      const fileArray = file.name.split('.')
      const suffix = fileArray[fileArray.length - 1]
      if (!suffix) {
        result = false
        return result
      }
      const xlslist = ['xls', 'xlsx']
      result = xlslist.some(function (item) {
        return item === suffix
      })
      if (!result) {
        return '请选择xls，或者xlsx文件导入！'
      }
      this.readExcel(file).then(tabJson => {
        if (tabJson && tabJson.length > 0) {
          this.data = tabJson[0].sheet
          this.importVisible = true
          console.log('数据', this.data)
        }
      })
      // 不进行上传操作
      return false
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.uploadLoad = true
        this.$message.success('文件上传中，请勿刷新或关闭页面')
        return
      }
      if (info.file.status === 'done') {
        this.uploadLoad = false
        if (info.file.response.code === 0) {
          this.$message.success(`${info.file.name} 文件上传成功！`)
        } else {
          this.$message.error(`${info.file.name}` + info.file.response.message)
        }
        // this.$refs.table.refresh()
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败！`)
        this.uploadLoad = false
      }
    },
    readExcel (file) { // 解析Excel
      // const _this = this
      return new Promise(function (resolve, reject) { // 返回Promise对象
        const reader = new FileReader()
        reader.onload = (e) => { // 异步执行
          try {
            // 以二进制流方式读取得到整份excel表格对象
            const data = e.target.result
            const workbook = XLSX.read(data, { type: 'binary' })
            // let batteryArr = [];
            const result = []
            for (const item in workbook.SheetNames) {
              const SheetName = workbook.SheetNames[item]
              const sheetInfos = workbook.Sheets[SheetName]
              const arr = []
              const outdata = XLSX.utils.sheet_to_json(sheetInfos)
              outdata.map(v => {
                const obj = {}
                obj.sn = v.sn
                obj.xyz = v.欧外
                // obj.deviceName = v.设备名称
                // obj.categoryName = v.设备分类
                // obj.distribuName = v.设备分布地
                // obj.categoryId = v.设备分类ID
                // obj.distribuId = v.设备分布地ID
                arr.push(obj)
              })
              result.push({
                sheetName: SheetName,
                sheet: arr
              })
            }
            resolve(result)
          } catch (e) {
            reject(e.message)
          }
        }
        reader.readAsBinaryString(file)
      })
    },
    handleImportCancel (visible) {
      if (!visible) {
        this.importVisible = false
      }
    },

    handleReadExcel (file) {
      const that = this
      const fileReader = new FileReader()
      fileReader.onload = ev => {
        try {
          const fileData = ev.target.result
          const workbook = XLSX.read(fileData, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0] // 取第一张表
          const snArr = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
          // console.log(snArr) // 读取到的SN列表
          // 遍历SN放入Set集合 snSet
          that.dataGrid.snSet.clear() // 清空一下之前的Set
          snArr.forEach(item => {
            that.dataGrid.snSet.add(item.sn)
          })
          // console.log(that.dataGrid.snSet)
          // 处理完SN列表之后可以开放OK按钮
          this.enableSubmit = false
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    }
  }
}

</script>

<style scoped>

</style>
